import axios from "axios"
const { VITE_API_URL } = import.meta.env

const request = axios.create({
    baseURL: VITE_API_URL,
    withCredentials: true,
})

const CONSTANCE = {
    // 请求成功
    SUCCESS: 200,
    // 请求失败
    FAIL: 400,
    // 未登录
    UNLOGIN: 401,
    // 权限不足
    UNAUTH: 403,
    // 服务器错误
    ERROR: 500,
}

request.interceptors.request.use(
    (config) => {
        return config
    },
    (err) => {
        return [false, err];
    }
)

request.interceptors.response.use(
    (res) => {
        const { data } = res
        let success = false

        switch(data.code) {
            case CONSTANCE.SUCCESS:
                success = true
                break
            case CONSTANCE.UNLOGIN:
                window.alert('登录过期，请重新登录')
                window.location.href = '/login'
                break
            default:
                window.alert('请求失败')
                break
        }
        return [success, data?.data]
    },
    (err) => {
        const { response } = err;
        if (response) {
            switch (response.status) {
                case CONSTANCE.UNLOGIN:
                    window.alert('登录过期，请重新登录')
                    window.location.href = '/login'
                    break
                default:
                    window.alert('请求失败')
                    break
            }
             // 统一返回错误的响应
             return [false, response.data || response];
        }
        return [false, err]
    }
)


export default request  